<template>
  <div>
    <Modal v-model="userForm" :title="isEdit? '编辑' : '新增'" :loading="loading" @on-ok="submit">
      <formCreate :rule="rule" :option="option" v-model="formData"></formCreate>
    </Modal>
  </div>
</template>

<script>
import option from './options'
import { findComponentUpward } from '@/libs/util'
import axios from 'axios'
import crudApi from '@/libs/mixins/crud-api'
export default {
  name: 'formModal',
  mixins: [crudApi],
  props: {
    url: String,
    delKey: {
      type: Array,
      default: () => []
    },
    rule: Array
  },
  data () {
    return {
      isEdit: false,
      loading: true,
      userForm: false,
      formData: {},
      option
    }
  },
  watch: {

  },
  methods: {

    async submit () {
      this.formData.submit(
        async data => {
          this.delKey.map(key => delete data[key])

          if (this.isEdit) {
            await this.edit(data)
              .then(d => {
                this.$Message.success('编辑成功')
                this.$emit('success', d, this.isEdit)
              })
              .catch(err => this.$Message.error('编辑失败'))
          } else {
            await this.add(data)
              .then(d => {
                this.$Message.success('添加成功')
                this.$emit('success', d, this.isEdit)
              })
              .catch(err => this.$Message.error('添加失败'))
          }
          this.userForm = false
        },
        () => {
          this.loading = false
          this.$nextTick(() => {
            this.loading = true
          })
        }
      )
    },

    setKey (key, val) {
      let fields = this.formData.fields()
      if (fields.includes(key)) {
        this.formData.setValue(key, val)
      } else {
        this.formData.append({ type: 'hidden', field: key, value: val })
      }
    },

    /**
     * 显示form
    */
    show (isEdit = false) {
      this.isEdit = isEdit
      this.userForm = true
    }

  }
}
</script>
